<html>
	<head>
		<link rel="stylesheet" type="text/css" href="styles/main.css">
	</head>
	<body>
		<?php
		include('includes/hash_pass.php');
		include('config.php');
		// procedure (no seesion id, login):
		// 1. check name/pass against db, if correct:
		// 2. generate random session_id and create db entry
		// 3. create a cookie with session id
		// 
		// procedure (yes session id)
		// 1. check if current date is past expiration date
		// yes: re-login needed, go to above
		// 2. no: change last_on_date to date
		// 3. change expiration_date and update cookie expiration date
		
		$password = hash_pass($_POST['password']);
		$username = $_POST['username'];
		//echo "$username|$password<br>";
		$account_query = mysql_query("SELECT id FROM account WHERE username = '$username' AND password = '$password'");
		if(mysql_num_rows($account_query)>0)
		// account exists, check sessions
		{
			$account_ids = mysql_fetch_array($account_query);
			$account_id = $account_ids[0];
			
			$session_query = mysql_query("SELECT id FROM loginSession WHERE account_id = $account_id");
			if(mysql_num_rows($session_query)>0)
			// session exists, check if expired
			{
				$expired_query = mysql_query("SELECT id FROM loginSession WHERE CURDATE() <= FROM_UNIXTIME(expiration_date) AND account_id = $account_id") OR die(mysql_error());
				if(mysql_num_rows($expired_query)>0)
				{
				
				}
			}else{
			// no session exists so make 1
				$session_id = generateRandomString(30);
				$last_on_date = time();
				echo "yaaay|$account_id|$session_id";
				$expiration_date = $last_on_date + 60*60*24* 7;
				echo "<br>||INSERT INTO loginSession (session_id, account_id, last_on_date, expiration_date) VALUES ('$session_id','$account_id','$last_on_date','$expiration_date')||";
				mysql_query("INSERT INTO loginSession, account (loginSession.session_id, loginSession.account_id, loginSession.last_on_date, loginSession.expiration_date) VALUES ('$session_id','$account_id','$last_on_date','$expiration_date')") OR die(mysql_error());
			}echo "omg";
			//mysql_query("UPDATE loginSession ");
		}else{
		// account doesnt exists, propose register?
		
		}
		
		// succesfull login, redirect back
		$referer = $_SERVER['HTTP_REFERER'];
		echo "Succesfully logged in with |$username|.<br>";
		echo "Redirecting you to $referer in two seconds";
		echo "
		<script>
			setTimeout(function () {
				window.location.href = '$referer'; 
			}, 20000);
		</script>";
		?>
	</body>
</html>